import React, {Component} from 'react';
import {Icon, Upload} from 'antd';
import './index.css';

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function beforeUpload(file) {
    // const isJPG = file.type === 'image/jpeg';

    // if (!isJPG) {
    //     message.error('You can only upload JPG file!');
    // }
    // const isLt2M = file.size / 1024 / 1024 < 2;
    // if (!isLt2M) {
    //     message.error('Image must smaller than 2MB!');
    // }
    // return isJPG && isLt2M;

    return true;
}

export default class MUploadImg extends Component {

    static defaultProps = {
        imageUrl: '',
        onChange: null
    };

    constructor(props) {
        super(props);

        this.state = {
            imageUrl: this.props.imageUrl
        };

    }

    componentWillReceiveProps(nextProps) {
        const {imageUrl} = nextProps;

        if (this.state.imageUrl != imageUrl) {
            this.setState({
                imageUrl
            });
        }
    }

    render() {
        const {onChange} = this.props;
        const {imageUrl} = this.state;

        return (
            <Upload
                className="avatar-uploader"
                name="image"
                showUploadList={false}
                action="/openapi/UploadImg/upload"
                beforeUpload={beforeUpload}
                onChange={(info) => {
                    var response = info.file.response;
                    if (!response) {
                        onChange && onChange(new Error('上传失败'));
                        return;
                    }
                    var imgUrl = response.result.url;

                    this.setState({
                        imageUrl: imgUrl
                    });
                    onChange && onChange(null, imgUrl);
                }}
            >
                {
                    imageUrl ?
                        <div className="avatarWrap">
                            <img src={imageUrl} alt="" className="avatar"/>
                            <div
                                onClick={(e) => {
                                    e.stopPropagation();
                                    this.setState({
                                        imageUrl: ''
                                    });
                                    onChange && onChange(null, '');
                                }}
                                className="avatar__del"
                            >删除
                            </div>
                        </div>
                        :
                        <Icon type="plus" className="avatar-uploader-trigger"/>
                }
            </Upload>
        );
    }
}